import json

from django.contrib.auth import logout

from apps.ausers.utils import generate_verify_email_url, check_verify_email_token

from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
import re
from django import http
from django.shortcuts import render, redirect
from django.urls import reverse
# Create your views here.
from django.views import View

from apps.ausers.models import User, Address
from apps.goods.models import SKU
from meiduo_mall.settings.dev import logger
#1注册页面
from utils.response_code import RETCODE
from django_redis import get_redis_connection

from utils.secret import SecretOauth


class RegisterView(View):
    """用户注册"""

    def get(self, request):
        """
        提供注册界面
        :param request: 请求对象
        :return: 注册界面
        """
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        return render(request, 'register.html',context)

    def post(self,request):

    # 1.实现后台功能---接收参数（request.POST）-检验参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
    # sms_code	string	是	短信验证码
        sms_code = request.POST.get('sms_code')
    #2校验参数
    #1判空
        if not all([username,password,password2,mobile]):
            return http.HttpResponseForbidden('参数不能为空')
    #2用户名-----判空 判正则 是否重复
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')
    #密码-------判空 判正则
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
    #确认密码----判空判相等
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
    #手机号------判空 判正则 判重复
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
    #图形验证码

    #6短信验证码
            # 6.短信验证码:
            # 6.1.导包
            # 6.2.链接
            sms_redis_client = get_redis_connection('sms_code')

            # 6.3 取值
            sms_redis_code = sms_redis_client.get("sms_%s" % mobile)

            # 6.4 判断
            if sms_redis_code is None:
                return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})

            # 千万注意: redis取出来的bytes.decode()
            if sms_code != sms_redis_code.decode():
                return render(request, 'register.html', {'sms_code_errmsg': '短信验证码验证失败!'})
    #7同意用户协议--判断是否选中
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')
    #3注册用户 create_user()
        try:
            from apps.ausers.models import User
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            logger.info(e)
            return render(request,'register.html',{'register_message':'注册失败'})

        login(request,user)

    #4返回响应

        # return redirect('/')
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', username, max_age=14 * 3600 * 24)
        return response

#2判断用户名重复
class UsernameCountView(View):
    def get(self,request,username):
        #1接收用户名 username
        #2判断空正则
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')
        #3逻辑数据库查询
        try:
            count = User.objects.get(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseForbidden('不存在')
         #4返回给前端 json
        return http.JsonResponse({'code':RETCODE.OK,'reemsg':'查询成功','count':count})

#3判断手机号重复
class MobileCountView(View):
    def get(self,request,mobile):
        #1.接收参数 mobile

        #2.检验参数 判空 判正则

        #3.数据库查询个数
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseForbidden('手机号不存在')
        #4.返回前端个数
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})
        pass

#4登陆页显示
class LoginView(View):
    def get(self,request):
        return render(request,'login.html')

    def post(self,request):
    # 2接受参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')
    #3解析检验 判空 判正则
    #4数据交互
        from django.contrib.auth import authenticate
        user = authenticate(username=username,password=password)
    #登陆失败
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})

        #5保持登录状态

        from django.contrib.auth import login
        login(request,user)
        #6记住登陆
        if remembered != 'on':
            #不记住 ---绘画结束失效
            request.session.set_expiry(0)
        else:
            #记住
            request.session.set_expiry(None)

        # next 记录上一个页面的路由
        next = request.GET.get('next')
        if next:
            response = redirect(next)
        else:
        #7跳转首页 index
            response = redirect(reverse('contents:index'))
        response.set_cookie('username', username, max_age=14 * 3600 * 24)
        return response
        #

#5退出
class LogoutView(LoginRequiredMixin,View):
    def get(self, request):
        from django.contrib.auth import logout

        # 退出 登录 logout
        logout(request)

        # 调到 login.html
        response = redirect(reverse('users:login'))
        # 删除cookie
        response.delete_cookie('username')

        return response

#6用户中心
class UserInfoView(LoginRequiredMixin,View):
    def get(self,request):
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            # 'email_active': request.user.email_actives
        }

        return render(request,'user_center_info.html',context)

#7修改邮箱的值
class EmailView(LoginRequiredMixin,View):
    def put(self, request):
        # json_str = request.body.decode()
        # json_dict = json.loads(json_str)
        email = json.load(request.body.decode()).get('email')

        # 正则校验
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('参数email有误')
        # 修改数据库的 email字段
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败'})

        #发邮件
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email)
        # 发送激活邮件
        verify_url = generate_verify_email_url(request.user)
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email, verify_url)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})

#8.激活邮箱 emails/verification/
class VerifyEmailView(LoginRequiredMixin,View):
    def get(self,request):
        # 1接收参数 秘文
        token = request.GET.get('token')
        #2解密
        token_dict = SecretOauth().loads(token)
        #3校验user
        try:
            user = User.objects.get(id=token_dict['user_id'],email=token_dict['email'])
        except Exception as e:
            logger.error(e)
            return http.HttpResponseForbidden('无效的token')
        #4改 email_active字段
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseForbidden('激活邮件失败')
        # 校验参数：判断token是否为空和过期，提取user
        # if not token:
        #     return http.HttpResponseBadRequest('缺少token')
        #
        # user = check_verify_email_token(token)
        # if not user:
        #     return http.HttpResponseForbidden('无效的token')

        # 修改email_active的值为True


        # 返回邮箱验证结果
        return redirect(reverse('users:info'))


#9.显示收货地址
class AddressView(LoginRequiredMixin,View):
    def get(self,request):
        #1获取所有的地址 未删除的
        user = request.user
        # addresses = Address.objects,filter(user=user, is_deleted=False)
        addresses = Address.objects.filter(user=user, is_deleted=False)

        #2构建前端的数据
        address_dict_list = []
        for address in addresses:
            address_dict_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })

        context = {
            'default_address_id': user.default_address_id,
            'addresses': address_dict_list,
        }

        return render(request, 'user_center_site.html')

#10新增地址
class CreateAddressView(LoginRequiredMixin,View):
    def post(self, request):

        #判断 地址个数 如果大于20 不允许增加
        count = Address.objects.filter(user=request.user,is_deleted=True).count()
        count = request.user.addresses.filter(is_deleted=True).count()
        if count > 20:
                return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})


        #1接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')




        #2校验 判空 判正则

        #3交互数据库 Address.objects.create()
        try:
            address = Address.objects.create(
                user = request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )

            #判断 用户是否有 默认地址 如果没有 设置一个
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})
        #4构建前端的数据格式 字典{}
        # address = Address.objects.get(user=request.user)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '新增地址成功', 'address': address_dict})

#11修改和删除地址
class UpdateDestroyAddressView(LoginRequiredMixin,View):
    def put(self,request,address_id):
        # 1接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')


        # 2校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')


        # 3修改  Address.objects.filter().update()
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址失败'})


        # 4返回前端 --dict
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '更新地址成功', 'address': address_dict})


    def delete(self,request,address_id):
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            # 响应删除地址结果
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除地址失败'})

            # 响应删除地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除地址成功'})

#12设置默认地址
class DefaultAddressView(LoginRequiredMixin,View):
    def put(self,request,address_id):
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置默认地址失败'})

    # 响应设置默认地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功'})

#13设置标题
class TitleAddressView(LoginRequiredMixin,View):
    def put(self,request,address_id):

        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            #1取出当前的地址
            address = Address.objects.get(id=address_id)

            #2修改title值
            address.title = title
            #3保存
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置地址标题失败'})

            # 4.响应删除地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置地址标题成功'})


class ChangePwdView(LoginRequiredMixin,View):
    def get(self, request):
        """展示修改密码界面"""
        return render(request, 'user_center_pass.html')

#14修改密码
class ChangePasswordView(LoginRequiredMixin, View):
    """修改密码"""

    def get(self, request):
        """展示修改密码界面"""
        return render(request, 'user_center_pass.html')

    def post(self, request):
        """实现修改密码逻辑"""
        # 接收参数
        old_password = request.POST.get('old_pwd')
        new_password = request.POST.get('new_pwd')
        new_password2 = request.POST.get('new_cpwd')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return http.HttpResponseForbidden('缺少必传参数')
        try:
            request.user.check_password(old_password)
        except Exception as e:
            logger.error(e)
            return render(request, 'user_center_pass.html', {'origin_pwd_errmsg':'原始密码错误'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')
        if new_password != new_password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return render(request, 'user_center_pass.html', {'change_pwd_errmsg': '修改密码失败'})

        # 清理状态保持信息
        logout(request)
        response = redirect(reverse('users:login'))
        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response

#15浏览记录
class HistoriesBrowseView(LoginRequiredMixin, View):
    def get(self, request):
        # *   1. 取出redis的 sku_ids
        redis_client = get_redis_connection('history')
        sku_ids = redis_client.lrange('history_' + str(request.user.id), 0, -1)

        # *   2.遍历sku_ids 取出数据库对应商品SKU
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                "default_image_url": sku.default_image.url,
                "price": sku.price
            })
        # *   3. 返回前端
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'skus': skus})

    def post(self, request):
        # 1.解析 sku_id
        sku_id = json.loads(request.body.decode()).get('sku_id')

        # 2.校验
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden('商品不存在!')

        # 3. 存redis
        redis_client = get_redis_connection('history')
        redis_key = 'history_' + str(request.user.id)

        p1 = redis_client.pipeline()

        # 3.1 先去重
        p1.lrem(redis_key, 0, sku_id)
        # 3.2 再存储
        p1.lpush(redis_key, sku_id)
        # 3.3 截取
        p1.ltrim(redis_key, 0, 4)

        p1.execute()

        # 4 返回
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
